package bb.lanxing.util.io;

import static bb.lanxing.model.database.RouteBook.TYPE_SOURCE_CREATE;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.litepal.LitePal;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.baidu.mapapi.model.LatLng;
import com.github.mikephil.charting.utils.Utils;

import android.text.TextUtils;

import bb.lanxing.activity.deeplink.DeepLinkPathConstants;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.data.Notepoint;
import bb.lanxing.model.database.RouteBook;
import bb.lanxing.model.database.RouteBookPoint;
import bb.lanxing.model.database.Waypoint;
import bb.lanxing.model.database.Workout;
import bb.lanxing.util.DistanceUtil;

public class SaxGpxImporter extends DefaultHandler {
    private static final String ATT_LAT = "lat";
    private static final String ATT_LON = "lon";
    private static final String TAG_TRKPT = "trkpt";
    private static final String TAG_WPT = "wpt";
    private final RouteBook routeBook;
    private final List<RouteBookPoint> bufferedPoints = new ArrayList(512);
    private final List<Waypoint> bufferedWaypoints = new ArrayList();
    private final List<Notepoint> notepointList = new ArrayList();
    private final NameDescCombiner nameDescCombiner = new NameDescCombiner();
    private String content;
    private double distance;
    private Notepoint notepoint;
    private RouteBookPoint prePoint;

    public SaxGpxImporter(RouteBook routeBook) {
        this.routeBook = routeBook;
    }

    public static long importGPXFile(File gpxFile) throws ParserConfigurationException, SAXException, IOException {
        SAXParser newSAXParser = SAXParserFactory.newInstance().newSAXParser();
        RouteBook routeBook = new RouteBook();
        routeBook.setImported(false);
        routeBook.setSport(Workout.TYPE_CYCLING);
        routeBook.setCreateTime(System.currentTimeMillis());
        String name = gpxFile.getName();
        if (name.endsWith(DeepLinkPathConstants.FILE_SUFFIX_GPX)) {
            routeBook.setTitle(name.substring(0, name.indexOf(DeepLinkPathConstants.FILE_SUFFIX_GPX)));
        }
        routeBook.setUuid(UUID.randomUUID().toString());
        routeBook.setSourceType(RouteBook.TYPE_IMPORT);
        routeBook.setServerType(TYPE_SOURCE_CREATE);
        routeBook.setUserId(SharedManager.getInstance().getUserId());
        routeBook.setFileName(gpxFile.getName());
        routeBook.save();
        try {
            newSAXParser.parse(gpxFile, new SaxGpxImporter(routeBook));
            return routeBook.getId();
        } catch (Exception e) {
            e.printStackTrace();
            LitePal.delete(RouteBook.class, routeBook.getId());
            return 0L;
        }
    }

    private static double getDistance(RouteBookPoint p1, RouteBookPoint p2) {
        return DistanceUtil.get(p1.getLatitude(), p1.getLongitude(), p2.getLatitude(), p2.getLongitude());
    }

    @Override
    public void characters(char[] ch2, int start, int length) throws SAXException {
        String str = new String(ch2, start, length);
        if (this.content == null) {
            this.content = str;
            return;
        }
        this.content += str;
    }

    @Override
    public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
        if (localName.equals(TAG_TRKPT)) {
            onTrackPointElementStart(attributes);
        } else if (localName.equals(TAG_WPT)) {
            onWayPointElementStart(attributes);
        }
    }

    @Override
    public void endElement(String uri, String localName, String name) throws SAXException {
        if (localName.equals("name")) {
            onNameElementEnd();
        } else if (localName.equals("desc")) {
            onDescElementEnd();
        } else if (localName.equals("gpx")) {
            onGpxElementEnd();
        } else if (localName.equals(TAG_WPT)) {
            onWayPointElementEnd();
        }
        this.content = null;
    }

    private void onDistanceElementEnd() {
        String str = this.content;
        if (str != null) {
            try {
                this.routeBook.setDistance(Double.parseDouble(str) * 1000.0d);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void onNameElementEnd() {
        String str = this.content;
        if (str != null) {
            if (this.notepoint != null) {
                this.nameDescCombiner.name = str.trim();
            } else if (TextUtils.isEmpty(this.routeBook.getTitle())) {
                this.routeBook.setTitle(this.content.trim());
            }
        }
    }

    private void onDescElementEnd() {
        String str = this.content;
        if (str == null || this.notepoint == null) {
            return;
        }
        this.nameDescCombiner.desc = str.trim();
    }

    private void onGpxElementEnd() {
        flushPoints();
        for (Waypoint waypoint : this.bufferedWaypoints) {
            waypoint.save();
        }
        this.routeBook.setNotepointJsonArray(Notepoint.toJsonArray(this.notepointList));
        if (this.routeBook.getDistance() == Utils.DOUBLE_EPSILON) {
            this.routeBook.setDistance(this.distance);
        }
        this.routeBook.setImported(true);
        this.routeBook.save();
    }

    private void onWayPointElementStart(Attributes attributes) throws SAXException {
        LatLng latLng = getLatLng(attributes);
        if (latLng == null) {
            return;
        }
        Notepoint notepoint = new Notepoint();
        this.notepoint = notepoint;
        notepoint.setLatitude(latLng.latitude);
        this.notepoint.setLongitude(latLng.longitude);
        this.notepointList.add(this.notepoint);
    }

    private void onWayPointElementEnd() {
        this.notepoint.setTitle(this.nameDescCombiner.getContent());
        this.nameDescCombiner.reset();
    }

    private void onTrackPointElementStart(Attributes attributes) throws SAXException {
        LatLng latLng = getLatLng(attributes);
        if (latLng == null) {
            return;
        }
        RouteBookPoint lushuPoint = new RouteBookPoint();
        lushuPoint.setLushuId(this.routeBook.getId());
        lushuPoint.setLatlng(latLng);
        insertPoint(lushuPoint);
        RouteBookPoint lushuPoint2 = this.prePoint;
        if (lushuPoint2 != null) {
            this.distance += getDistance(lushuPoint2, lushuPoint);
        }
        this.prePoint = lushuPoint;
    }

    private void insertPoint(RouteBookPoint point) {
        this.bufferedPoints.add(point);
        if (this.bufferedPoints.size() == 512) {
            flushPoints();
        }
    }

    private void flushPoints() {
        if (this.bufferedPoints.isEmpty()) {
            return;
        }
        RouteBookPoint.savePoints(this.bufferedPoints);
        this.bufferedPoints.clear();
    }

    private LatLng getLatLng(Attributes attributes) {
        String value = attributes.getValue("lat");
        String value2 = attributes.getValue(ATT_LON);
        if (value == null || value2 == null) {
            return null;
        }
        try {
            return new LatLng(Double.parseDouble(value), Double.parseDouble(value2));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
